import React, { useState, useEffect, useRef } from 'react';

const AudioPlayer = ({ audioSources, onPlayEnd, startIndex = 0, loop = true }) => {
  const audioRef = useRef(null);
  const [currentAudioIndex, setCurrentAudioIndex] = useState(startIndex);
  const [isPlaying, setIsPlaying] = useState(false);

  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.addEventListener('ended', handleAudioEnd);
      return () => {
        audioRef.current.removeEventListener('ended', handleAudioEnd);
      };
    }
  }, []);

  const handleAudioEnd = () => {
    if (loop) {
      let nextIndex = currentAudioIndex + 1;
      if (nextIndex >= audioSources.length) {
        nextIndex = 0;
      }
      setCurrentAudioIndex(nextIndex);
      // 直接在这里控制播放，而不是在 state 更新后等待
      if (audioRef.current) {
        // 监听audioRef.current 是否load完成 
        audioRef.current.addEventListener('canplaythrough', () => {
          audioRef.current.play().catch(error => {
            console.error('Error playing audio:', error);
          });
        });
        // audioRef.current.play().catch(error => {
        //   console.error('Error playing audio:', error);
        // });
      }
    } else {
      setIsPlaying(false);
    }
    onPlayEnd(currentAudioIndex);
  };

  useEffect(() => {
    if (isPlaying && audioRef.current) {
      audioRef.current.play().catch(error => {
        console.error('Error playing audio:', error);
      });
    }
  }, [isPlaying]);

  return (
    <div>
      {audioSources && audioSources.length > 0 && (
        <audio
          ref={audioRef}
          src={audioSources[currentAudioIndex]}
          // 移除 autoPlay={true}，因为我们将在 state 控制下手动触发播放
          controls
        />
      )}
    </div>
  );
};

export default AudioPlayer;